package com.lanou3g.demo;

import java.io.*;
import java.net.Socket;

public class SocketRunnable implements Runnable {

    private Socket socket;

    public SocketRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            // 获取到输入流, 读取客户端发送过来的数据
            InputStream in = socket.getInputStream();
            InputStreamReader r = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(r);
            // 获取输出流, 用来给客户端发送数据
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(out);
            PrintWriter p = new PrintWriter(w);
            System.out.println("客户端已连接, 开始读取客户端发送过来的数据");

            String address = socket.getInetAddress().getHostAddress();
            while (true){
                String word = br.readLine();
                System.out.println(address + "客户端说: " + word);
                if (word == null || word.equals("bye")){
                    break;
                }
                System.out.println("服务端回复客户端");
                p.println(word);
                p.flush();
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
